package com.youlu.campus.service.ca;

import com.youlu.campus.entity.*;
import com.youlu.campus.service.ca.impl.CaCertificateConfigService;
import com.youlu.campus.service.ca.impl.CertificateActivityConfigService;
import com.youlu.campus.service.cache.CacheActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserPaperCaReceiveHistoryService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CertificateActivityConfigService certificateActivityConfigService;

    @Autowired
    private CaCertificateConfigService caCertificateConfigService;

    @Autowired
    private CaTemplateService caTemplateService;

    @Autowired
    private CacheActivityService cacheActivityService;


    public void initPaperOrder(String activityId){
        log.info("【初始化小程序订单纸质证书】activityId:{}",activityId);
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        query.addCriteria(Criteria.where("status").nin("0","9","6"));
        List<OrderInfo> orderInfoList = this.mongoTemplate.find(query, OrderInfo.class);
        if(CollectionUtils.isEmpty(orderInfoList)){
            log.error("【初始化小程序订单纸质证书】 未找到相关订单 activityId:{}",activityId);
            return;
        }
        orderInfoList.stream().forEach(orderInfo -> {
            Query  subQuery = new Query();
            subQuery.addCriteria(Criteria.where("orderNo").is(orderInfo.getOrderNo()));
            List<OOrderInfo> subOrderList = this.mongoTemplate.find(subQuery, OOrderInfo.class);
            subOrderList.stream().forEach(oOrderInfo -> {
                CaInfo caInfo = oOrderInfo.getCaInfo();
                if(!caInfo.getCaGift()){
                    CaGroupInfo caGroupInfo = this.mongoTemplate.findById(caInfo.getCaGroupInfoId(), CaGroupInfo.class);
                    CertificateActivityConfig certificateActivityConfig =
                            certificateActivityConfigService.findByActivityIdAndBizType(activityId, caGroupInfo.getTaskBizType());
                    CaCertificateConfig caCertificateConfig =
                            caCertificateConfigService.findByActivityIdAndCaTypeAndCaLevel(activityId, caGroupInfo.getTaskBizType()
                                    , caInfo.getLevel());
                    CaTemplate caTemplate = caTemplateService.detail(caCertificateConfig.getTemplateId());
                    UserPaperCaReceiveHistory userCaReceiveHistory = new UserPaperCaReceiveHistory();
                    userCaReceiveHistory.setUserId(orderInfo.getAccountInfoId());
                    userCaReceiveHistory.setActivityId(activityId);
                    userCaReceiveHistory.setActivityName(certificateActivityConfig.getActivityName());
                    userCaReceiveHistory.setCaLevel(caInfo.getLevel());
                    userCaReceiveHistory.setCaTemplateImgUrl(caTemplate.getBackgroundPic().getUrl());
                    userCaReceiveHistory.setCaType(caGroupInfo.getTaskBizType());
                    userCaReceiveHistory.setCaTemplateId(caTemplate.getId());
                    userCaReceiveHistory.setReceiveTime(certificateActivityConfig.getCaTime());
                    userCaReceiveHistory.setAppId(orderInfo.getAppId());
                    userCaReceiveHistory.setPlatform(orderInfo.getPlatform());
                    this.saveOrUpdate(userCaReceiveHistory);
                }else {
                    log.error("【初始化小程序订单纸质证书】 礼品 orderNo:{} levle:{}",orderInfo.getOrderNo(),caInfo.getLevel());
                }
            });
        });
        orderInfoList.clear();
        log.info("【初始化小程序订单纸质证书】 end activityId:{}",activityId);

    }


    @Async
    public void saveOrUpdate(UserPaperCaReceiveHistory userPaperCaReceiveHistory){
        String userId = userPaperCaReceiveHistory.getUserId();
        String caType = userPaperCaReceiveHistory.getCaType();
        String caLevel = userPaperCaReceiveHistory.getCaLevel();
        String activityId = userPaperCaReceiveHistory.getActivityId();
        if(StringUtils.isBlank(userId)||StringUtils.isBlank(caType)||StringUtils.isBlank(caLevel)||StringUtils.isBlank(activityId)){
            log.error("【纸质证书领取】插入或更新缺少必传参数");
            return;
        }
        log.info("【领取纸质版】userId:{}|caType:{}|caLevel:{}|activityId:{}",userId,caLevel,caLevel,activityId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("caType").is(caType));
        query.addCriteria(Criteria.where("caLevel").is(caLevel));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        Update update = new Update();
        Date now =new Date();
        boolean exists = this.mongoTemplate.exists(query, UserPaperCaReceiveHistory.class);
        if(!exists){
            update.set("createdTime",now);
        }
        update.set("updatedTime",now);
        if(Objects.nonNull(userPaperCaReceiveHistory.getReceiveTime())){
            update.set("receiveTime",userPaperCaReceiveHistory.getReceiveTime());
        }
        if(StringUtils.isNotBlank(userPaperCaReceiveHistory.getCaTemplateId())){
            update.set("caTemplateId",userPaperCaReceiveHistory.getCaTemplateId());
        }
        if(StringUtils.isNotBlank(userPaperCaReceiveHistory.getCaTemplateImgUrl())){
            update.set("caTemplateImgUrl",userPaperCaReceiveHistory.getCaTemplateImgUrl());
        }
        if(StringUtils.isNotBlank(userPaperCaReceiveHistory.getAppId())){
            update.set("appId",userPaperCaReceiveHistory.getAppId());
        }
        if(StringUtils.isNotBlank(userPaperCaReceiveHistory.getActivityName())){
            update.set("activityName",userPaperCaReceiveHistory.getActivityName());
        }

        if(StringUtils.isNotBlank(userPaperCaReceiveHistory.getPlatform())){
            update.set("platform",userPaperCaReceiveHistory.getPlatform());
        }
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.upsert(Boolean.TRUE);
        findAndModifyOptions.returnNew(Boolean.TRUE);
        this.mongoTemplate.findAndModify(query,update,findAndModifyOptions,UserPaperCaReceiveHistory.class);
    }
}
